home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / perl / 5.10.0 / Archive / Tar.pm < prev   
Encoding:
Perl POD Document  |  2009-06-26  |  58.6 KB  |  1,908 lines

  1. ### the gnu tar specification:
  2. ### http://www.gnu.org/software/tar/manual/tar.html
  3. ###
  4. ### and the pax format spec, which tar derives from:
  5. ### http://www.opengroup.org/onlinepubs/007904975/utilities/pax.html
  6.  
  7. package Archive::Tar;
  8. require 5.005_03;
  9.  
  10. use strict;
  11. use vars qw[$DEBUG $error $VERSION $WARN $FOLLOW_SYMLINK $CHOWN $CHMOD
  12.             $DO_NOT_USE_PREFIX $HAS_PERLIO $HAS_IO_STRING
  13.             $INSECURE_EXTRACT_MODE
  14.          ];
  15.  
  16. $DEBUG                  = 0;
  17. $WARN                   = 1;
  18. $FOLLOW_SYMLINK         = 0;
  19. $VERSION                = "1.38";
  20. $CHOWN                  = 1;
  21. $CHMOD                  = 1;
  22. $DO_NOT_USE_PREFIX      = 0;
  23. $INSECURE_EXTRACT_MODE  = 0;
  24.  
  25. BEGIN {
  26.     use Config;
  27.     $HAS_PERLIO = $Config::Config{useperlio};
  28.  
  29.     ### try and load IO::String anyway, so you can dynamically
  30.     ### switch between perlio and IO::String
  31.     eval {
  32.         require IO::String;
  33.         import IO::String;
  34.     };
  35.     $HAS_IO_STRING = $@ ? 0 : 1;
  36.  
  37. }
  38.  
  39. use Cwd;
  40. use IO::File;
  41. use Carp                qw(carp croak);
  42. use File::Spec          ();
  43. use File::Spec::Unix    ();
  44. use File::Path          ();
  45.  
  46. use Archive::Tar::File;
  47. use Archive::Tar::Constant;
  48.  
  49. =head1 NAME
  50.  
  51. Archive::Tar - module for manipulations of tar archives
  52.  
  53. =head1 SYNOPSIS
  54.  
  55.     use Archive::Tar;
  56.     my $tar = Archive::Tar->new;
  57.  
  58.     $tar->read('origin.tgz',1);
  59.     $tar->extract();
  60.  
  61.     $tar->add_files('file/foo.pl', 'docs/README');
  62.     $tar->add_data('file/baz.txt', 'This is the contents now');
  63.  
  64.     $tar->rename('oldname', 'new/file/name');
  65.  
  66.     $tar->write('files.tar');
  67.  
  68. =head1 DESCRIPTION
  69.  
  70. Archive::Tar provides an object oriented mechanism for handling tar
  71. files.  It provides class methods for quick and easy files handling
  72. while also allowing for the creation of tar file objects for custom
  73. manipulation.  If you have the IO::Zlib module installed,
  74. Archive::Tar will also support compressed or gzipped tar files.
  75.  
  76. An object of class Archive::Tar represents a .tar(.gz) archive full
  77. of files and things.
  78.  
  79. =head1 Object Methods
  80.  
  81. =head2 Archive::Tar->new( [$file, $compressed] )
  82.  
  83. Returns a new Tar object. If given any arguments, C<new()> calls the
  84. C<read()> method automatically, passing on the arguments provided to
  85. the C<read()> method.
  86.  
  87. If C<new()> is invoked with arguments and the C<read()> method fails
  88. for any reason, C<new()> returns undef.
  89.  
  90. =cut
  91.  
  92. my $tmpl = {
  93.     _data   => [ ],
  94.     _file   => 'Unknown',
  95. };
  96.  
  97. ### install get/set accessors for this object.
  98. for my $key ( keys %$tmpl ) {
  99.     no strict 'refs';
  100.     *{__PACKAGE__."::$key"} = sub {
  101.         my $self = shift;
  102.         $self->{$key} = $_[0] if @_;
  103.         return $self->{$key};
  104.     }
  105. }
  106.  
  107. sub new {
  108.     my $class = shift;
  109.     $class = ref $class if ref $class;
  110.  
  111.     ### copying $tmpl here since a shallow copy makes it use the
  112.     ### same aref, causing for files to remain in memory always.
  113.     my $obj = bless { _data => [ ], _file => 'Unknown' }, $class;
  114.  
  115.     if (@_) {
  116.         unless ( $obj->read( @_ ) ) {
  117.             $obj->_error(qq[No data could be read from file]);
  118.             return;
  119.         }
  120.     }
  121.  
  122.     return $obj;
  123. }
  124.  
  125. =head2 $tar->read ( $filename|$handle, $compressed, {opt => 'val'} )
  126.  
  127. Read the given tar file into memory.
  128. The first argument can either be the name of a file or a reference to
  129. an already open filehandle (or an IO::Zlib object if it's compressed)
  130. The second argument indicates whether the file referenced by the first
  131. argument is compressed.
  132.  
  133. The C<read> will I<replace> any previous content in C<$tar>!
  134.  
  135. The second argument may be considered optional if IO::Zlib is
  136. installed, since it will transparently Do The Right Thing.
  137. Archive::Tar will warn if you try to pass a compressed file if
  138. IO::Zlib is not available and simply return.
  139.  
  140. Note that you can currently B<not> pass a C<gzip> compressed
  141. filehandle, which is not opened with C<IO::Zlib>, nor a string
  142. containing the full archive information (either compressed or
  143. uncompressed). These are worth while features, but not currently
  144. implemented. See the C<TODO> section.
  145.  
  146. The third argument can be a hash reference with options. Note that
  147. all options are case-sensitive.
  148.  
  149. =over 4
  150.  
  151. =item limit
  152.  
  153. Do not read more than C<limit> files. This is useful if you have
  154. very big archives, and are only interested in the first few files.
  155.  
  156. =item extract
  157.  
  158. If set to true, immediately extract entries when reading them. This
  159. gives you the same memory break as the C<extract_archive> function.
  160. Note however that entries will not be read into memory, but written
  161. straight to disk.
  162.  
  163. =back
  164.  
  165. All files are stored internally as C<Archive::Tar::File> objects.
  166. Please consult the L<Archive::Tar::File> documentation for details.
  167.  
  168. Returns the number of files read in scalar context, and a list of
  169. C<Archive::Tar::File> objects in list context.
  170.  
  171. =cut
  172.  
  173. sub read {
  174.     my $self = shift;
  175.     my $file = shift;
  176.     my $gzip = shift || 0;
  177.     my $opts = shift || {};
  178.  
  179.     unless( defined $file ) {
  180.         $self->_error( qq[No file to read from!] );
  181.         return;
  182.     } else {
  183.         $self->_file( $file );
  184.     }
  185.  
  186.     my $handle = $self->_get_handle($file, $gzip, READ_ONLY->( ZLIB ) )
  187.                     or return;
  188.  
  189.     my $data = $self->_read_tar( $handle, $opts ) or return;
  190.  
  191.     $self->_data( $data );
  192.  
  193.     return wantarray ? @$data : scalar @$data;
  194. }
  195.  
  196. sub _get_handle {
  197.     my $self = shift;
  198.     my $file = shift;   return unless defined $file;
  199.                         return $file if ref $file;
  200.  
  201.     my $gzip = shift || 0;
  202.     my $mode = shift || READ_ONLY->( ZLIB ); # default to read only
  203.  
  204.     my $fh; my $bin;
  205.  
  206.     ### only default to ZLIB if we're not trying to /write/ to a handle ###
  207.     if( ZLIB and $gzip || MODE_READ->( $mode ) ) {
  208.  
  209.         ### IO::Zlib will Do The Right Thing, even when passed
  210.         ### a plain file ###
  211.         $fh = new IO::Zlib;
  212.  
  213.     } else {
  214.         if( $gzip ) {
  215.             $self->_error(qq[Compression not available - Install IO::Zlib!]);
  216.             return;
  217.  
  218.         } else {
  219.             $fh = new IO::File;
  220.             $bin++;
  221.         }
  222.     }
  223.  
  224.     unless( $fh->open( $file, $mode ) ) {
  225.         $self->_error( qq[Could not create filehandle for '$file': $!!] );
  226.         return;
  227.     }
  228.  
  229.     binmode $fh if $bin;
  230.  
  231.     return $fh;
  232. }
  233.  
  234. sub _read_tar {
  235.     my $self    = shift;
  236.     my $handle  = shift or return;
  237.     my $opts    = shift || {};
  238.  
  239.     my $count   = $opts->{limit}    || 0;
  240.     my $extract = $opts->{extract}  || 0;
  241.  
  242.     ### set a cap on the amount of files to extract ###
  243.     my $limit   = 0;
  244.     $limit = 1 if $count > 0;
  245.  
  246.     my $tarfile = [ ];
  247.     my $chunk;
  248.     my $read = 0;
  249.     my $real_name;  # to set the name of a file when
  250.                     # we're encountering @longlink
  251.     my $data;
  252.  
  253.     LOOP:
  254.     while( $handle->read( $chunk, HEAD ) ) {
  255.         ### IO::Zlib doesn't support this yet
  256.         my $offset = eval { tell $handle } || 'unknown';
  257.  
  258.         unless( $read++ ) {
  259.             my $gzip = GZIP_MAGIC_NUM;
  260.             if( $chunk =~ /$gzip/ ) {
  261.                 $self->_error( qq[Cannot read compressed format in tar-mode] );
  262.                 return;
  263.             }
  264.         }
  265.  
  266.         ### if we can't read in all bytes... ###
  267.         last if length $chunk != HEAD;
  268.  
  269.         ### Apparently this should really be two blocks of 512 zeroes,
  270.         ### but GNU tar sometimes gets it wrong. See comment in the
  271.         ### source code (tar.c) to GNU cpio.
  272.         next if $chunk eq TAR_END;
  273.  
  274.         ### according to the posix spec, the last 12 bytes of the header are
  275.         ### null bytes, to pad it to a 512 byte block. That means if these
  276.         ### bytes are NOT null bytes, it's a corrrupt header. See:
  277.         ### www.koders.com/c/fidCE473AD3D9F835D690259D60AD5654591D91D5BA.aspx
  278.         ### line 111
  279.         {   my $nulls = join '', "\0" x 12;
  280.             unless( $nulls eq substr( $chunk, 500, 12 ) ) {
  281.                 $self->_error( qq[Invalid header block at offset $offset] );
  282.                 next LOOP;
  283.             }
  284.         }
  285.  
  286.         ### pass the realname, so we can set it 'proper' right away
  287.         ### some of the heuristics are done on the name, so important
  288.         ### to set it ASAP
  289.         my $entry;
  290.         {   my %extra_args = ();
  291.             $extra_args{'name'} = $$real_name if defined $real_name;
  292.             
  293.             unless( $entry = Archive::Tar::File->new(   chunk => $chunk, 
  294.                                                         %extra_args ) 
  295.             ) {
  296.                 $self->_error( qq[Couldn't read chunk at offset $offset] );
  297.                 next LOOP;
  298.             }
  299.         }
  300.  
  301.         ### ignore labels:
  302.         ### http://www.gnu.org/manual/tar/html_node/tar_139.html
  303.         next if $entry->is_label;
  304.  
  305.         if( length $entry->type and ($entry->is_file || $entry->is_longlink) ) {
  306.  
  307.             if ( $entry->is_file && !$entry->validate ) {
  308.                 ### sometimes the chunk is rather fux0r3d and a whole 512
  309.                 ### bytes ends up in the ->name area.
  310.                 ### clean it up, if need be
  311.                 my $name = $entry->name;
  312.                 $name = substr($name, 0, 100) if length $name > 100;
  313.                 $name =~ s/\n/ /g;
  314.  
  315.                 $self->_error( $name . qq[: checksum error] );
  316.                 next LOOP;
  317.             }
  318.  
  319.             my $block = BLOCK_SIZE->( $entry->size );
  320.  
  321.             $data = $entry->get_content_by_ref;
  322.  
  323.             ### just read everything into memory
  324.             ### can't do lazy loading since IO::Zlib doesn't support 'seek'
  325.             ### this is because Compress::Zlib doesn't support it =/
  326.             ### this reads in the whole data in one read() call.
  327.             if( $handle->read( $$data, $block ) < $block ) {
  328.                 $self->_error( qq[Read error on tarfile (missing data) '].
  329.                                     $entry->full_path ."' at offset $offset" );
  330.                 next LOOP;
  331.             }
  332.  
  333.             ### throw away trailing garbage ###
  334.             substr ($$data, $entry->size) = "" if defined $$data;
  335.  
  336.             ### part II of the @LongLink munging -- need to do /after/
  337.             ### the checksum check.
  338.             if( $entry->is_longlink ) {
  339.                 ### weird thing in tarfiles -- if the file is actually a
  340.                 ### @LongLink, the data part seems to have a trailing ^@
  341.                 ### (unprintable) char. to display, pipe output through less.
  342.                 ### but that doesn't *always* happen.. so check if the last
  343.                 ### character is a control character, and if so remove it
  344.                 ### at any rate, we better remove that character here, or tests
  345.                 ### like 'eq' and hashlook ups based on names will SO not work
  346.                 ### remove it by calculating the proper size, and then
  347.                 ### tossing out everything that's longer than that size.
  348.  
  349.                 ### count number of nulls
  350.                 my $nulls = $$data =~ tr/\0/\0/;
  351.  
  352.                 ### cut data + size by that many bytes
  353.                 $entry->size( $entry->size - $nulls );
  354.                 substr ($$data, $entry->size) = "";
  355.             }
  356.         }
  357.  
  358.         ### clean up of the entries.. posix tar /apparently/ has some
  359.         ### weird 'feature' that allows for filenames > 255 characters
  360.         ### they'll put a header in with as name '././@LongLink' and the
  361.         ### contents will be the name of the /next/ file in the archive
  362.         ### pretty crappy and kludgy if you ask me
  363.  
  364.         ### set the name for the next entry if this is a @LongLink;
  365.         ### this is one ugly hack =/ but needed for direct extraction
  366.         if( $entry->is_longlink ) {
  367.             $real_name = $data;
  368.             next LOOP;
  369.         } elsif ( defined $real_name ) {
  370.             $entry->name( $$real_name );
  371.             $entry->prefix('');
  372.             undef $real_name;
  373.         }
  374.  
  375.         $self->_extract_file( $entry ) if $extract
  376.                                             && !$entry->is_longlink
  377.                                             && !$entry->is_unknown
  378.                                             && !$entry->is_label;
  379.  
  380.         ### Guard against tarfiles with garbage at the end
  381.         last LOOP if $entry->name eq '';
  382.  
  383.         ### push only the name on the rv if we're extracting
  384.         ### -- for extract_archive
  385.         push @$tarfile, ($extract ? $entry->name : $entry);
  386.  
  387.         if( $limit ) {
  388.             $count-- unless $entry->is_longlink || $entry->is_dir;
  389.             last LOOP unless $count;
  390.         }
  391.     } continue {
  392.         undef $data;
  393.     }
  394.  
  395.     return $tarfile;
  396. }
  397.  
  398. =head2 $tar->contains_file( $filename )
  399.  
  400. Check if the archive contains a certain file.
  401. It will return true if the file is in the archive, false otherwise.
  402.  
  403. Note however, that this function does an exact match using C<eq>
  404. on the full path. So it cannot compensate for case-insensitive file-
  405. systems or compare 2 paths to see if they would point to the same
  406. underlying file.
  407.  
  408. =cut
  409.  
  410. sub contains_file {
  411.     my $self = shift;
  412.     my $full = shift;
  413.     
  414.     return unless defined $full;
  415.  
  416.     ### don't warn if the entry isn't there.. that's what this function
  417.     ### is for after all.
  418.     local $WARN = 0;
  419.     return 1 if $self->_find_entry($full);
  420.     return;
  421. }
  422.  
  423. =head2 $tar->extract( [@filenames] )
  424.  
  425. Write files whose names are equivalent to any of the names in
  426. C<@filenames> to disk, creating subdirectories as necessary. This
  427. might not work too well under VMS.
  428. Under MacPerl, the file's modification time will be converted to the
  429. MacOS zero of time, and appropriate conversions will be done to the
  430. path.  However, the length of each element of the path is not
  431. inspected to see whether it's longer than MacOS currently allows (32
  432. characters).
  433.  
  434. If C<extract> is called without a list of file names, the entire
  435. contents of the archive are extracted.
  436.  
  437. Returns a list of filenames extracted.
  438.  
  439. =cut
  440.  
  441. sub extract {
  442.     my $self    = shift;
  443.     my @args    = @_;
  444.     my @files;
  445.  
  446.     # use the speed optimization for all extracted files
  447.     local($self->{cwd}) = cwd() unless $self->{cwd};
  448.  
  449.     ### you requested the extraction of only certian files
  450.     if( @args ) {
  451.         for my $file ( @args ) {
  452.             
  453.             ### it's already an object?
  454.             if( UNIVERSAL::isa( $file, 'Archive::Tar::File' ) ) {
  455.                 push @files, $file;
  456.                 next;
  457.  
  458.             ### go find it then
  459.             } else {
  460.             
  461.                 my $found;
  462.                 for my $entry ( @{$self->_data} ) {
  463.                     next unless $file eq $entry->full_path;
  464.     
  465.                     ### we found the file you're looking for
  466.                     push @files, $entry;
  467.                     $found++;
  468.                 }
  469.     
  470.                 unless( $found ) {
  471.                     return $self->_error( 
  472.                         qq[Could not find '$file' in archive] );
  473.                 }
  474.             }
  475.         }
  476.  
  477.     ### just grab all the file items
  478.     } else {
  479.         @files = $self->get_files;
  480.     }
  481.  
  482.     ### nothing found? that's an error
  483.     unless( scalar @files ) {
  484.         $self->_error( qq[No files found for ] . $self->_file );
  485.         return;
  486.     }
  487.  
  488.     ### now extract them
  489.     for my $entry ( @files ) {
  490.         unless( $self->_extract_file( $entry ) ) {
  491.             $self->_error(q[Could not extract ']. $entry->full_path .q['] );
  492.             return;
  493.         }
  494.     }
  495.  
  496.     return @files;
  497. }
  498.  
  499. =head2 $tar->extract_file( $file, [$extract_path] )
  500.  
  501. Write an entry, whose name is equivalent to the file name provided to
  502. disk. Optionally takes a second parameter, which is the full native
  503. path (including filename) the entry will be written to.
  504.  
  505. For example:
  506.  
  507.     $tar->extract_file( 'name/in/archive', 'name/i/want/to/give/it' );
  508.  
  509.     $tar->extract_file( $at_file_object,   'name/i/want/to/give/it' );
  510.  
  511. Returns true on success, false on failure.
  512.  
  513. =cut
  514.  
  515. sub extract_file {
  516.     my $self = shift;
  517.     my $file = shift;   return unless defined $file;
  518.     my $alt  = shift;
  519.  
  520.     my $entry = $self->_find_entry( $file )
  521.         or $self->_error( qq[Could not find an entry for '$file'] ), return;
  522.  
  523.     return $self->_extract_file( $entry, $alt );
  524. }
  525.  
  526. sub _extract_file {
  527.     my $self    = shift;
  528.     my $entry   = shift or return;
  529.     my $alt     = shift;
  530.  
  531.     ### you wanted an alternate extraction location ###
  532.     my $name = defined $alt ? $alt : $entry->full_path;
  533.  
  534.                             ### splitpath takes a bool at the end to indicate
  535.                             ### that it's splitting a dir
  536.     my ($vol,$dirs,$file);
  537.     if ( defined $alt ) { # It's a local-OS path
  538.         ($vol,$dirs,$file) = File::Spec->splitpath(       $alt,
  539.                                                           $entry->is_dir );
  540.     } else {
  541.         ($vol,$dirs,$file) = File::Spec::Unix->splitpath( $name,
  542.                                                           $entry->is_dir );
  543.     }
  544.  
  545.     my $dir;
  546.     ### is $name an absolute path? ###
  547.     if( File::Spec->file_name_is_absolute( $dirs ) ) {
  548.  
  549.         ### absolute names are not allowed to be in tarballs under
  550.         ### strict mode, so only allow it if a user tells us to do it
  551.         if( not defined $alt and not $INSECURE_EXTRACT_MODE ) {
  552.             $self->_error( 
  553.                 q[Entry ']. $entry->full_path .q[' is an absolute path. ].
  554.                 q[Not extracting absolute paths under SECURE EXTRACT MODE]
  555.             );  
  556.             return;
  557.         }
  558.         
  559.         ### user asked us to, it's fine.
  560.         $dir = $dirs;
  561.  
  562.     ### it's a relative path ###
  563.     } else {
  564.         my $cwd     = (ref $self and defined $self->{cwd}) 
  565.                         ? $self->{cwd} 
  566.                         : cwd();
  567.  
  568.         my @dirs = defined $alt
  569.             ? File::Spec->splitdir( $dirs )         # It's a local-OS path
  570.             : File::Spec::Unix->splitdir( $dirs );  # it's UNIX-style, likely
  571.                                                     # straight from the tarball
  572.  
  573.         if( not defined $alt            and 
  574.             not $INSECURE_EXTRACT_MODE 
  575.         ) {            
  576.  
  577.             ### paths that leave the current directory are not allowed under
  578.             ### strict mode, so only allow it if a user tells us to do this.
  579.             if( grep { $_ eq '..' } @dirs ) {
  580.     
  581.                 $self->_error(
  582.                     q[Entry ']. $entry->full_path .q[' is attempting to leave ].
  583.                     q[the current working directory. Not extracting under ].
  584.                     q[SECURE EXTRACT MODE]
  585.                 );
  586.                 return;
  587.             } 
  588.         
  589.             ### the archive may be asking us to extract into a symlink. This
  590.             ### is not sane and a possible security issue, as outlined here:
  591.             ### https://rt.cpan.org/Ticket/Display.html?id=30380
  592.             ### https://bugzilla.redhat.com/show_bug.cgi?id=295021
  593.             ### https://issues.rpath.com/browse/RPL-1716
  594.             my $full_path = $cwd;
  595.             for my $d ( @dirs ) {
  596.                 $full_path = File::Spec->catdir( $full_path, $d );
  597.                 
  598.                 ### we've already checked this one, and it's safe. Move on.
  599.                 next if ref $self and $self->{_link_cache}->{$full_path};
  600.  
  601.                 if( -l $full_path ) {
  602.                     my $to   = readlink $full_path;
  603.                     my $diag = "symlinked directory ($full_path => $to)";
  604.  
  605.                     $self->_error(
  606.                         q[Entry ']. $entry->full_path .q[' is attempting to ].
  607.                         qq[extract to a $diag. This is considered a security ].
  608.                         q[vulnerability and not allowed under SECURE EXTRACT ].
  609.                         q[MODE]
  610.                     );
  611.                     return;
  612.                 }
  613.                 
  614.                 ### XXX keep a cache if possible, so the stats become cheaper:
  615.                 $self->{_link_cache}->{$full_path} = 1 if ref $self;
  616.             }
  617.         }
  618.  
  619.         
  620.         ### '.' is the directory delimiter, of which the first one has to
  621.         ### be escaped/changed.
  622.         map tr/\./_/, @dirs if ON_VMS;        
  623.  
  624.         my ($cwd_vol,$cwd_dir,$cwd_file) 
  625.                     = File::Spec->splitpath( $cwd );
  626.         my @cwd     = File::Spec->splitdir( $cwd_dir );
  627.         push @cwd, $cwd_file if length $cwd_file;
  628.  
  629.         ### We need to pass '' as the last elemant to catpath. Craig Berry
  630.         ### explains why (msgid <p0624083dc311ae541393@[172.16.52.1]>):
  631.         ### The root problem is that splitpath on UNIX always returns the 
  632.         ### final path element as a file even if it is a directory, and of
  633.         ### course there is no way it can know the difference without checking
  634.         ### against the filesystem, which it is documented as not doing.  When
  635.         ### you turn around and call catpath, on VMS you have to know which bits
  636.         ### are directory bits and which bits are file bits.  In this case we
  637.         ### know the result should be a directory.  I had thought you could omit
  638.         ### the file argument to catpath in such a case, but apparently on UNIX
  639.         ### you can't.
  640.         $dir        = File::Spec->catpath( 
  641.                             $cwd_vol, File::Spec->catdir( @cwd, @dirs ), '' 
  642.                         );
  643.  
  644.         ### catdir() returns undef if the path is longer than 255 chars on VMS
  645.         unless ( defined $dir ) {
  646.             $^W && $self->_error( qq[Could not compose a path for '$dirs'\n] );
  647.             return;
  648.         }
  649.  
  650.     }
  651.  
  652.     if( -e $dir && !-d _ ) {
  653.         $^W && $self->_error( qq['$dir' exists, but it's not a directory!\n] );
  654.         return;
  655.     }
  656.  
  657.     unless ( -d _ ) {
  658.         eval { File::Path::mkpath( $dir, 0, 0777 ) };
  659.         if( $@ ) {
  660.             my $fp = $entry->full_path;
  661.             $self->_error(qq[Could not create directory '$dir' for '$fp': $@]);
  662.             return;
  663.         }
  664.         
  665.         ### XXX chown here? that might not be the same as in the archive
  666.         ### as we're only chown'ing to the owner of the file we're extracting
  667.         ### not to the owner of the directory itself, which may or may not
  668.         ### be another entry in the archive
  669.         ### Answer: no, gnu tar doesn't do it either, it'd be the wrong
  670.         ### way to go.
  671.         #if( $CHOWN && CAN_CHOWN ) {
  672.         #    chown $entry->uid, $entry->gid, $dir or
  673.         #        $self->_error( qq[Could not set uid/gid on '$dir'] );
  674.         #}
  675.     }
  676.  
  677.     ### we're done if we just needed to create a dir ###
  678.     return 1 if $entry->is_dir;
  679.  
  680.     my $full = File::Spec->catfile( $dir, $file );
  681.  
  682.     if( $entry->is_unknown ) {
  683.         $self->_error( qq[Unknown file type for file '$full'] );
  684.         return;
  685.     }
  686.  
  687.     if( length $entry->type && $entry->is_file ) {
  688.         my $fh = IO::File->new;
  689.         $fh->open( '>' . $full ) or (
  690.             $self->_error( qq[Could not open file '$full': $!] ),
  691.             return
  692.         );
  693.  
  694.         if( $entry->size ) {
  695.             binmode $fh;
  696.             syswrite $fh, $entry->data or (
  697.                 $self->_error( qq[Could not write data to '$full'] ),
  698.                 return
  699.             );
  700.         }
  701.  
  702.         close $fh or (
  703.             $self->_error( qq[Could not close file '$full'] ),
  704.             return
  705.         );
  706.  
  707.     } else {
  708.         $self->_make_special_file( $entry, $full ) or return;
  709.     }
  710.  
  711.     ### only update the timestamp if it's not a symlink; that will change the
  712.     ### timestamp of the original. This addresses bug #33669: Could not update
  713.     ### timestamp warning on symlinks
  714.     if( not -l $full ) {
  715.         utime time, $entry->mtime - TIME_OFFSET, $full or
  716.             $self->_error( qq[Could not update timestamp] );
  717.     }
  718.  
  719.     if( $CHOWN && CAN_CHOWN ) {
  720.         chown $entry->uid, $entry->gid, $full or
  721.             $self->_error( qq[Could not set uid/gid on '$full'] );
  722.     }
  723.  
  724.     ### only chmod if we're allowed to, but never chmod symlinks, since they'll
  725.     ### change the perms on the file they're linking too...
  726.     if( $CHMOD and not -l $full ) {
  727.         chmod $entry->mode, $full or
  728.             $self->_error( qq[Could not chown '$full' to ] . $entry->mode );
  729.     }
  730.  
  731.     return 1;
  732. }
  733.  
  734. sub _make_special_file {
  735.     my $self    = shift;
  736.     my $entry   = shift     or return;
  737.     my $file    = shift;    return unless defined $file;
  738.  
  739.     my $err;
  740.  
  741.     if( $entry->is_symlink ) {
  742.         my $fail;
  743.         if( ON_UNIX ) {
  744.             symlink( $entry->linkname, $file ) or $fail++;
  745.  
  746.         } else {
  747.             $self->_extract_special_file_as_plain_file( $entry, $file )
  748.                 or $fail++;
  749.         }
  750.  
  751.         $err =  qq[Making symbolic link '$file' to '] .
  752.                 $entry->linkname .q[' failed] if $fail;
  753.  
  754.     } elsif ( $entry->is_hardlink ) {
  755.         my $fail;
  756.         if( ON_UNIX ) {
  757.             link( $entry->linkname, $file ) or $fail++;
  758.  
  759.         } else {
  760.             $self->_extract_special_file_as_plain_file( $entry, $file )
  761.                 or $fail++;
  762.         }
  763.  
  764.         $err =  qq[Making hard link from '] . $entry->linkname .
  765.                 qq[' to '$file' failed] if $fail;
  766.  
  767.     } elsif ( $entry->is_fifo ) {
  768.         ON_UNIX && !system('mknod', $file, 'p') or
  769.             $err = qq[Making fifo ']. $entry->name .qq[' failed];
  770.  
  771.     } elsif ( $entry->is_blockdev or $entry->is_chardev ) {
  772.         my $mode = $entry->is_blockdev ? 'b' : 'c';
  773.  
  774.         ON_UNIX && !system('mknod', $file, $mode,
  775.                             $entry->devmajor, $entry->devminor) or
  776.             $err =  qq[Making block device ']. $entry->name .qq[' (maj=] .
  777.                     $entry->devmajor . qq[ min=] . $entry->devminor .
  778.                     qq[) failed.];
  779.  
  780.     } elsif ( $entry->is_socket ) {
  781.         ### the original doesn't do anything special for sockets.... ###
  782.         1;
  783.     }
  784.  
  785.     return $err ? $self->_error( $err ) : 1;
  786. }
  787.  
  788. ### don't know how to make symlinks, let's just extract the file as
  789. ### a plain file
  790. sub _extract_special_file_as_plain_file {
  791.     my $self    = shift;
  792.     my $entry   = shift     or return;
  793.     my $file    = shift;    return unless defined $file;
  794.  
  795.     my $err;
  796.     TRY: {
  797.         my $orig = $self->_find_entry( $entry->linkname );
  798.  
  799.         unless( $orig ) {
  800.             $err =  qq[Could not find file '] . $entry->linkname .
  801.                     qq[' in memory.];
  802.             last TRY;
  803.         }
  804.  
  805.         ### clone the entry, make it appear as a normal file ###
  806.         my $clone = $entry->clone;
  807.         $clone->_downgrade_to_plainfile;
  808.         $self->_extract_file( $clone, $file ) or last TRY;
  809.  
  810.         return 1;
  811.     }
  812.  
  813.     return $self->_error($err);
  814. }
  815.  
  816. =head2 $tar->list_files( [\@properties] )
  817.  
  818. Returns a list of the names of all the files in the archive.
  819.  
  820. If C<list_files()> is passed an array reference as its first argument
  821. it returns a list of hash references containing the requested
  822. properties of each file.  The following list of properties is
  823. supported: name, size, mtime (last modified date), mode, uid, gid,
  824. linkname, uname, gname, devmajor, devminor, prefix.
  825.  
  826. Passing an array reference containing only one element, 'name', is
  827. special cased to return a list of names rather than a list of hash
  828. references, making it equivalent to calling C<list_files> without
  829. arguments.
  830.  
  831. =cut
  832.  
  833. sub list_files {
  834.     my $self = shift;
  835.     my $aref = shift || [ ];
  836.  
  837.     unless( $self->_data ) {
  838.         $self->read() or return;
  839.     }
  840.  
  841.     if( @$aref == 0 or ( @$aref == 1 and $aref->[0] eq 'name' ) ) {
  842.         return map { $_->full_path } @{$self->_data};
  843.     } else {
  844.  
  845.         #my @rv;
  846.         #for my $obj ( @{$self->_data} ) {
  847.         #    push @rv, { map { $_ => $obj->$_() } @$aref };
  848.         #}
  849.         #return @rv;
  850.  
  851.         ### this does the same as the above.. just needs a +{ }
  852.         ### to make sure perl doesn't confuse it for a block
  853.         return map {    my $o=$_;
  854.                         +{ map { $_ => $o->$_() } @$aref }
  855.                     } @{$self->_data};
  856.     }
  857. }
  858.  
  859. sub _find_entry {
  860.     my $self = shift;
  861.     my $file = shift;
  862.  
  863.     unless( defined $file ) {
  864.         $self->_error( qq[No file specified] );
  865.         return;
  866.     }
  867.  
  868.     ### it's an object already
  869.     return $file if UNIVERSAL::isa( $file, 'Archive::Tar::File' );
  870.  
  871.     for my $entry ( @{$self->_data} ) {
  872.         my $path = $entry->full_path;
  873.         return $entry if $path eq $file;
  874.     }
  875.  
  876.     $self->_error( qq[No such file in archive: '$file'] );
  877.     return;
  878. }
  879.  
  880. =head2 $tar->get_files( [@filenames] )
  881.  
  882. Returns the C<Archive::Tar::File> objects matching the filenames
  883. provided. If no filename list was passed, all C<Archive::Tar::File>
  884. objects in the current Tar object are returned.
  885.  
  886. Please refer to the C<Archive::Tar::File> documentation on how to
  887. handle these objects.
  888.  
  889. =cut
  890.  
  891. sub get_files {
  892.     my $self = shift;
  893.  
  894.     return @{ $self->_data } unless @_;
  895.  
  896.     my @list;
  897.     for my $file ( @_ ) {
  898.         push @list, grep { defined } $self->_find_entry( $file );
  899.     }
  900.  
  901.     return @list;
  902. }
  903.  
  904. =head2 $tar->get_content( $file )
  905.  
  906. Return the content of the named file.
  907.  
  908. =cut
  909.  
  910. sub get_content {
  911.     my $self = shift;
  912.     my $entry = $self->_find_entry( shift ) or return;
  913.  
  914.     return $entry->data;
  915. }
  916.  
  917. =head2 $tar->replace_content( $file, $content )
  918.  
  919. Make the string $content be the content for the file named $file.
  920.  
  921. =cut
  922.  
  923. sub replace_content {
  924.     my $self = shift;
  925.     my $entry = $self->_find_entry( shift ) or return;
  926.  
  927.     return $entry->replace_content( shift );
  928. }
  929.  
  930. =head2 $tar->rename( $file, $new_name )
  931.  
  932. Rename the file of the in-memory archive to $new_name.
  933.  
  934. Note that you must specify a Unix path for $new_name, since per tar
  935. standard, all files in the archive must be Unix paths.
  936.  
  937. Returns true on success and false on failure.
  938.  
  939. =cut
  940.  
  941. sub rename {
  942.     my $self = shift;
  943.     my $file = shift; return unless defined $file;
  944.     my $new  = shift; return unless defined $new;
  945.  
  946.     my $entry = $self->_find_entry( $file ) or return;
  947.  
  948.     return $entry->rename( $new );
  949. }
  950.  
  951. =head2 $tar->remove (@filenamelist)
  952.  
  953. Removes any entries with names matching any of the given filenames
  954. from the in-memory archive. Returns a list of C<Archive::Tar::File>
  955. objects that remain.
  956.  
  957. =cut
  958.  
  959. sub remove {
  960.     my $self = shift;
  961.     my @list = @_;
  962.  
  963.     my %seen = map { $_->full_path => $_ } @{$self->_data};
  964.     delete $seen{ $_ } for @list;
  965.  
  966.     $self->_data( [values %seen] );
  967.  
  968.     return values %seen;
  969. }
  970.  
  971. =head2 $tar->clear
  972.  
  973. C<clear> clears the current in-memory archive. This effectively gives
  974. you a 'blank' object, ready to be filled again. Note that C<clear>
  975. only has effect on the object, not the underlying tarfile.
  976.  
  977. =cut
  978.  
  979. sub clear {
  980.     my $self = shift or return;
  981.  
  982.     $self->_data( [] );
  983.     $self->_file( '' );
  984.  
  985.     return 1;
  986. }
  987.  
  988.  
  989. =head2 $tar->write ( [$file, $compressed, $prefix] )
  990.  
  991. Write the in-memory archive to disk.  The first argument can either
  992. be the name of a file or a reference to an already open filehandle (a
  993. GLOB reference). If the second argument is true, the module will use
  994. IO::Zlib to write the file in a compressed format.  If IO::Zlib is
  995. not available, the C<write> method will fail and return.
  996.  
  997. Note that when you pass in a filehandle, the compression argument
  998. is ignored, as all files are printed verbatim to your filehandle.
  999. If you wish to enable compression with filehandles, use an
  1000. C<IO::Zlib> filehandle instead.
  1001.  
  1002. Specific levels of compression can be chosen by passing the values 2
  1003. through 9 as the second parameter.
  1004.  
  1005. The third argument is an optional prefix. All files will be tucked
  1006. away in the directory you specify as prefix. So if you have files
  1007. 'a' and 'b' in your archive, and you specify 'foo' as prefix, they
  1008. will be written to the archive as 'foo/a' and 'foo/b'.
  1009.  
  1010. If no arguments are given, C<write> returns the entire formatted
  1011. archive as a string, which could be useful if you'd like to stuff the
  1012. archive into a socket or a pipe to gzip or something.
  1013.  
  1014. =cut
  1015.  
  1016. sub write {
  1017.     my $self        = shift;
  1018.     my $file        = shift; $file = '' unless defined $file;
  1019.     my $gzip        = shift || 0;
  1020.     my $ext_prefix  = shift; $ext_prefix = '' unless defined $ext_prefix;
  1021.     my $dummy       = '';
  1022.     
  1023.     ### only need a handle if we have a file to print to ###
  1024.     my $handle = length($file)
  1025.                     ? ( $self->_get_handle($file, $gzip, WRITE_ONLY->($gzip) )
  1026.                         or return )
  1027.                     : $HAS_PERLIO    ? do { open my $h, '>', \$dummy; $h }
  1028.                     : $HAS_IO_STRING ? IO::String->new 
  1029.                     : __PACKAGE__->no_string_support();
  1030.  
  1031.  
  1032.  
  1033.     for my $entry ( @{$self->_data} ) {
  1034.         ### entries to be written to the tarfile ###
  1035.         my @write_me;
  1036.  
  1037.         ### only now will we change the object to reflect the current state
  1038.         ### of the name and prefix fields -- this needs to be limited to
  1039.         ### write() only!
  1040.         my $clone = $entry->clone;
  1041.  
  1042.  
  1043.         ### so, if you don't want use to use the prefix, we'll stuff 
  1044.         ### everything in the name field instead
  1045.         if( $DO_NOT_USE_PREFIX ) {
  1046.  
  1047.             ### you might have an extended prefix, if so, set it in the clone
  1048.             ### XXX is ::Unix right?
  1049.             $clone->name( length $ext_prefix
  1050.                             ? File::Spec::Unix->catdir( $ext_prefix,
  1051.                                                         $clone->full_path)
  1052.                             : $clone->full_path );
  1053.             $clone->prefix( '' );
  1054.  
  1055.         ### otherwise, we'll have to set it properly -- prefix part in the
  1056.         ### prefix and name part in the name field.
  1057.         } else {
  1058.  
  1059.             ### split them here, not before!
  1060.             my ($prefix,$name) = $clone->_prefix_and_file( $clone->full_path );
  1061.  
  1062.             ### you might have an extended prefix, if so, set it in the clone
  1063.             ### XXX is ::Unix right?
  1064.             $prefix = File::Spec::Unix->catdir( $ext_prefix, $prefix )
  1065.                 if length $ext_prefix;
  1066.  
  1067.             $clone->prefix( $prefix );
  1068.             $clone->name( $name );
  1069.         }
  1070.  
  1071.         ### names are too long, and will get truncated if we don't add a
  1072.         ### '@LongLink' file...
  1073.         my $make_longlink = (   length($clone->name)    > NAME_LENGTH or
  1074.                                 length($clone->prefix)  > PREFIX_LENGTH
  1075.                             ) || 0;
  1076.  
  1077.         ### perhaps we need to make a longlink file?
  1078.         if( $make_longlink ) {
  1079.             my $longlink = Archive::Tar::File->new(
  1080.                             data => LONGLINK_NAME,
  1081.                             $clone->full_path,
  1082.                             { type => LONGLINK }
  1083.                         );
  1084.  
  1085.             unless( $longlink ) {
  1086.                 $self->_error(  qq[Could not create 'LongLink' entry for ] .
  1087.                                 qq[oversize file '] . $clone->full_path ."'" );
  1088.                 return;
  1089.             };
  1090.  
  1091.             push @write_me, $longlink;
  1092.         }
  1093.  
  1094.         push @write_me, $clone;
  1095.  
  1096.         ### write the one, optionally 2 a::t::file objects to the handle
  1097.         for my $clone (@write_me) {
  1098.  
  1099.             ### if the file is a symlink, there are 2 options:
  1100.             ### either we leave the symlink intact, but then we don't write any
  1101.             ### data OR we follow the symlink, which means we actually make a
  1102.             ### copy. if we do the latter, we have to change the TYPE of the
  1103.             ### clone to 'FILE'
  1104.             my $link_ok =  $clone->is_symlink && $Archive::Tar::FOLLOW_SYMLINK;
  1105.             my $data_ok = !$clone->is_symlink && $clone->has_content;
  1106.  
  1107.             ### downgrade to a 'normal' file if it's a symlink we're going to
  1108.             ### treat as a regular file
  1109.             $clone->_downgrade_to_plainfile if $link_ok;
  1110.  
  1111.             ### get the header for this block
  1112.             my $header = $self->_format_tar_entry( $clone );
  1113.             unless( $header ) {
  1114.                 $self->_error(q[Could not format header for: ] .
  1115.                                     $clone->full_path );
  1116.                 return;
  1117.             }
  1118.  
  1119.             unless( print $handle $header ) {
  1120.                 $self->_error(q[Could not write header for: ] .
  1121.                                     $clone->full_path);
  1122.                 return;
  1123.             }
  1124.  
  1125.             if( $link_ok or $data_ok ) {
  1126.                 unless( print $handle $clone->data ) {
  1127.                     $self->_error(q[Could not write data for: ] .
  1128.                                     $clone->full_path);
  1129.                     return;
  1130.                 }
  1131.  
  1132.                 ### pad the end of the clone if required ###
  1133.                 print $handle TAR_PAD->( $clone->size ) if $clone->size % BLOCK
  1134.             }
  1135.  
  1136.         } ### done writing these entries
  1137.     }
  1138.  
  1139.     ### write the end markers ###
  1140.     print $handle TAR_END x 2 or
  1141.             return $self->_error( qq[Could not write tar end markers] );
  1142.  
  1143.     ### did you want it written to a file, or returned as a string? ###
  1144.     my $rv =  length($file) ? 1
  1145.                         : $HAS_PERLIO ? $dummy
  1146.                         : do { seek $handle, 0, 0; local $/; <$handle> };
  1147.  
  1148.     ### make sure to close the handle;
  1149.     close $handle;
  1150.     
  1151.     return $rv;
  1152. }
  1153.  
  1154. sub _format_tar_entry {
  1155.     my $self        = shift;
  1156.     my $entry       = shift or return;
  1157.     my $ext_prefix  = shift; $ext_prefix = '' unless defined $ext_prefix;
  1158.     my $no_prefix   = shift || 0;
  1159.  
  1160.     my $file    = $entry->name;
  1161.     my $prefix  = $entry->prefix; $prefix = '' unless defined $prefix;
  1162.  
  1163.     ### remove the prefix from the file name
  1164.     ### not sure if this is still neeeded --kane
  1165.     ### no it's not -- Archive::Tar::File->_new_from_file will take care of
  1166.     ### this for us. Even worse, this would break if we tried to add a file
  1167.     ### like x/x.
  1168.     #if( length $prefix ) {
  1169.     #    $file =~ s/^$match//;
  1170.     #}
  1171.  
  1172.     $prefix = File::Spec::Unix->catdir($ext_prefix, $prefix)
  1173.                 if length $ext_prefix;
  1174.  
  1175.     ### not sure why this is... ###
  1176.     my $l = PREFIX_LENGTH; # is ambiguous otherwise...
  1177.     substr ($prefix, 0, -$l) = "" if length $prefix >= PREFIX_LENGTH;
  1178.  
  1179.     my $f1 = "%06o"; my $f2  = "%11o";
  1180.  
  1181.     ### this might be optimizable with a 'changed' flag in the file objects ###
  1182.     my $tar = pack (
  1183.                 PACK,
  1184.                 $file,
  1185.  
  1186.                 (map { sprintf( $f1, $entry->$_() ) } qw[mode uid gid]),
  1187.                 (map { sprintf( $f2, $entry->$_() ) } qw[size mtime]),
  1188.  
  1189.                 "",  # checksum field - space padded a bit down
  1190.  
  1191.                 (map { $entry->$_() }                 qw[type linkname magic]),
  1192.  
  1193.                 $entry->version || TAR_VERSION,
  1194.  
  1195.                 (map { $entry->$_() }                 qw[uname gname]),
  1196.                 (map { sprintf( $f1, $entry->$_() ) } qw[devmajor devminor]),
  1197.  
  1198.                 ($no_prefix ? '' : $prefix)
  1199.     );
  1200.  
  1201.     ### add the checksum ###
  1202.     substr($tar,148,7) = sprintf("%6o\0", unpack("%16C*",$tar));
  1203.  
  1204.     return $tar;
  1205. }
  1206.  
  1207. =head2 $tar->add_files( @filenamelist )
  1208.  
  1209. Takes a list of filenames and adds them to the in-memory archive.
  1210.  
  1211. The path to the file is automatically converted to a Unix like
  1212. equivalent for use in the archive, and, if on MacOS, the file's
  1213. modification time is converted from the MacOS epoch to the Unix epoch.
  1214. So tar archives created on MacOS with B<Archive::Tar> can be read
  1215. both with I<tar> on Unix and applications like I<suntar> or
  1216. I<Stuffit Expander> on MacOS.
  1217.  
  1218. Be aware that the file's type/creator and resource fork will be lost,
  1219. which is usually what you want in cross-platform archives.
  1220.  
  1221. Returns a list of C<Archive::Tar::File> objects that were just added.
  1222.  
  1223. =cut
  1224.  
  1225. sub add_files {
  1226.     my $self    = shift;
  1227.     my @files   = @_ or return;
  1228.  
  1229.     my @rv;
  1230.     for my $file ( @files ) {
  1231.         unless( -e $file || -l $file ) {
  1232.             $self->_error( qq[No such file: '$file'] );
  1233.             next;
  1234.         }
  1235.  
  1236.         my $obj = Archive::Tar::File->new( file => $file );
  1237.         unless( $obj ) {
  1238.             $self->_error( qq[Unable to add file: '$file'] );
  1239.             next;
  1240.         }
  1241.  
  1242.         push @rv, $obj;
  1243.     }
  1244.  
  1245.     push @{$self->{_data}}, @rv;
  1246.  
  1247.     return @rv;
  1248. }
  1249.  
  1250. =head2 $tar->add_data ( $filename, $data, [$opthashref] )
  1251.  
  1252. Takes a filename, a scalar full of data and optionally a reference to
  1253. a hash with specific options.
  1254.  
  1255. Will add a file to the in-memory archive, with name C<$filename> and
  1256. content C<$data>. Specific properties can be set using C<$opthashref>.
  1257. The following list of properties is supported: name, size, mtime
  1258. (last modified date), mode, uid, gid, linkname, uname, gname,
  1259. devmajor, devminor, prefix, type.  (On MacOS, the file's path and
  1260. modification times are converted to Unix equivalents.)
  1261.  
  1262. Valid values for the file type are the following constants defined in
  1263. Archive::Tar::Constants:
  1264.  
  1265. =over 4
  1266.  
  1267. =item FILE
  1268.  
  1269. Regular file.
  1270.  
  1271. =item HARDLINK
  1272.  
  1273. =item SYMLINK
  1274.  
  1275. Hard and symbolic ("soft") links; linkname should specify target.
  1276.  
  1277. =item CHARDEV
  1278.  
  1279. =item BLOCKDEV
  1280.  
  1281. Character and block devices. devmajor and devminor should specify the major
  1282. and minor device numbers.
  1283.  
  1284. =item DIR
  1285.  
  1286. Directory.
  1287.  
  1288. =item FIFO
  1289.  
  1290. FIFO (named pipe).
  1291.  
  1292. =item SOCKET
  1293.  
  1294. Socket.
  1295.  
  1296. =back
  1297.  
  1298. Returns the C<Archive::Tar::File> object that was just added, or
  1299. C<undef> on failure.
  1300.  
  1301. =cut
  1302.  
  1303. sub add_data {
  1304.     my $self    = shift;
  1305.     my ($file, $data, $opt) = @_;
  1306.  
  1307.     my $obj = Archive::Tar::File->new( data => $file, $data, $opt );
  1308.     unless( $obj ) {
  1309.         $self->_error( qq[Unable to add file: '$file'] );
  1310.         return;
  1311.     }
  1312.  
  1313.     push @{$self->{_data}}, $obj;
  1314.  
  1315.     return $obj;
  1316. }
  1317.  
  1318. =head2 $tar->error( [$BOOL] )
  1319.  
  1320. Returns the current errorstring (usually, the last error reported).
  1321. If a true value was specified, it will give the C<Carp::longmess>
  1322. equivalent of the error, in effect giving you a stacktrace.
  1323.  
  1324. For backwards compatibility, this error is also available as
  1325. C<$Archive::Tar::error> although it is much recommended you use the
  1326. method call instead.
  1327.  
  1328. =cut
  1329.  
  1330. {
  1331.     $error = '';
  1332.     my $longmess;
  1333.  
  1334.     sub _error {
  1335.         my $self    = shift;
  1336.         my $msg     = $error = shift;
  1337.         $longmess   = Carp::longmess($error);
  1338.  
  1339.         ### set Archive::Tar::WARN to 0 to disable printing
  1340.         ### of errors
  1341.         if( $WARN ) {
  1342.             carp $DEBUG ? $longmess : $msg;
  1343.         }
  1344.  
  1345.         return;
  1346.     }
  1347.  
  1348.     sub error {
  1349.         my $self = shift;
  1350.         return shift() ? $longmess : $error;
  1351.     }
  1352. }
  1353.  
  1354. =head2 $tar->setcwd( $cwd );
  1355.  
  1356. C<Archive::Tar> needs to know the current directory, and it will run
  1357. C<Cwd::cwd()> I<every> time it extracts a I<relative> entry from the 
  1358. tarfile and saves it in the file system. (As of version 1.30, however,
  1359. C<Archive::Tar> will use the speed optimization described below 
  1360. automatically, so it's only relevant if you're using C<extract_file()>).
  1361.  
  1362. Since C<Archive::Tar> doesn't change the current directory internally
  1363. while it is extracting the items in a tarball, all calls to C<Cwd::cwd()>
  1364. can be avoided if we can guarantee that the current directory doesn't
  1365. get changed externally.
  1366.  
  1367. To use this performance boost, set the current directory via
  1368.  
  1369.     use Cwd;
  1370.     $tar->setcwd( cwd() );
  1371.  
  1372. once before calling a function like C<extract_file> and
  1373. C<Archive::Tar> will use the current directory setting from then on
  1374. and won't call C<Cwd::cwd()> internally. 
  1375.  
  1376. To switch back to the default behaviour, use
  1377.  
  1378.     $tar->setcwd( undef );
  1379.  
  1380. and C<Archive::Tar> will call C<Cwd::cwd()> internally again.
  1381.  
  1382. If you're using C<Archive::Tar>'s C<exract()> method, C<setcwd()> will
  1383. be called for you.
  1384.  
  1385. =cut 
  1386.  
  1387. sub setcwd {
  1388.     my $self     = shift;
  1389.     my $cwd      = shift;
  1390.  
  1391.     $self->{cwd} = $cwd;
  1392. }
  1393.  
  1394. =head2 $bool = $tar->has_io_string
  1395.  
  1396. Returns true if we currently have C<IO::String> support loaded.
  1397.  
  1398. Either C<IO::String> or C<perlio> support is needed to support writing 
  1399. stringified archives. Currently, C<perlio> is the preferred method, if
  1400. available.
  1401.  
  1402. See the C<GLOBAL VARIABLES> section to see how to change this preference.
  1403.  
  1404. =cut
  1405.  
  1406. sub has_io_string { return $HAS_IO_STRING; }
  1407.  
  1408. =head2 $bool = $tar->has_perlio
  1409.  
  1410. Returns true if we currently have C<perlio> support loaded.
  1411.  
  1412. This requires C<perl-5.8> or higher, compiled with C<perlio> 
  1413.  
  1414. Either C<IO::String> or C<perlio> support is needed to support writing 
  1415. stringified archives. Currently, C<perlio> is the preferred method, if
  1416. available.
  1417.  
  1418. See the C<GLOBAL VARIABLES> section to see how to change this preference.
  1419.  
  1420. =cut
  1421.  
  1422. sub has_perlio { return $HAS_PERLIO; }
  1423.  
  1424.  
  1425. =head1 Class Methods
  1426.  
  1427. =head2 Archive::Tar->create_archive($file, $compression, @filelist)
  1428.  
  1429. Creates a tar file from the list of files provided.  The first
  1430. argument can either be the name of the tar file to create or a
  1431. reference to an open file handle (e.g. a GLOB reference).
  1432.  
  1433. The second argument specifies the level of compression to be used, if
  1434. any.  Compression of tar files requires the installation of the
  1435. IO::Zlib module.  Specific levels of compression may be
  1436. requested by passing a value between 2 and 9 as the second argument.
  1437. Any other value evaluating as true will result in the default
  1438. compression level being used.
  1439.  
  1440. Note that when you pass in a filehandle, the compression argument
  1441. is ignored, as all files are printed verbatim to your filehandle.
  1442. If you wish to enable compression with filehandles, use an
  1443. C<IO::Zlib> filehandle instead.
  1444.  
  1445. The remaining arguments list the files to be included in the tar file.
  1446. These files must all exist. Any files which don't exist or can't be
  1447. read are silently ignored.
  1448.  
  1449. If the archive creation fails for any reason, C<create_archive> will
  1450. return false. Please use the C<error> method to find the cause of the
  1451. failure.
  1452.  
  1453. Note that this method does not write C<on the fly> as it were; it
  1454. still reads all the files into memory before writing out the archive.
  1455. Consult the FAQ below if this is a problem.
  1456.  
  1457. =cut
  1458.  
  1459. sub create_archive {
  1460.     my $class = shift;
  1461.  
  1462.     my $file    = shift; return unless defined $file;
  1463.     my $gzip    = shift || 0;
  1464.     my @files   = @_;
  1465.  
  1466.     unless( @files ) {
  1467.         return $class->_error( qq[Cowardly refusing to create empty archive!] );
  1468.     }
  1469.  
  1470.     my $tar = $class->new;
  1471.     $tar->add_files( @files );
  1472.     return $tar->write( $file, $gzip );
  1473. }
  1474.  
  1475. =head2 Archive::Tar->list_archive ($file, $compressed, [\@properties])
  1476.  
  1477. Returns a list of the names of all the files in the archive.  The
  1478. first argument can either be the name of the tar file to list or a
  1479. reference to an open file handle (e.g. a GLOB reference).
  1480.  
  1481. If C<list_archive()> is passed an array reference as its third
  1482. argument it returns a list of hash references containing the requested
  1483. properties of each file.  The following list of properties is
  1484. supported: full_path, name, size, mtime (last modified date), mode, 
  1485. uid, gid, linkname, uname, gname, devmajor, devminor, prefix.
  1486.  
  1487. See C<Archive::Tar::File> for details about supported properties.
  1488.  
  1489. Passing an array reference containing only one element, 'name', is
  1490. special cased to return a list of names rather than a list of hash
  1491. references.
  1492.  
  1493. =cut
  1494.  
  1495. sub list_archive {
  1496.     my $class   = shift;
  1497.     my $file    = shift; return unless defined $file;
  1498.     my $gzip    = shift || 0;
  1499.  
  1500.     my $tar = $class->new($file, $gzip);
  1501.     return unless $tar;
  1502.  
  1503.     return $tar->list_files( @_ );
  1504. }
  1505.  
  1506. =head2 Archive::Tar->extract_archive ($file, $gzip)
  1507.  
  1508. Extracts the contents of the tar file.  The first argument can either
  1509. be the name of the tar file to create or a reference to an open file
  1510. handle (e.g. a GLOB reference).  All relative paths in the tar file will
  1511. be created underneath the current working directory.
  1512.  
  1513. C<extract_archive> will return a list of files it extracted.
  1514. If the archive extraction fails for any reason, C<extract_archive>
  1515. will return false.  Please use the C<error> method to find the cause
  1516. of the failure.
  1517.  
  1518. =cut
  1519.  
  1520. sub extract_archive {
  1521.     my $class   = shift;
  1522.     my $file    = shift; return unless defined $file;
  1523.     my $gzip    = shift || 0;
  1524.  
  1525.     my $tar = $class->new( ) or return;
  1526.  
  1527.     return $tar->read( $file, $gzip, { extract => 1 } );
  1528. }
  1529.  
  1530. =head2 Archive::Tar->can_handle_compressed_files
  1531.  
  1532. A simple checking routine, which will return true if C<Archive::Tar>
  1533. is able to uncompress compressed archives on the fly with C<IO::Zlib>,
  1534. or false if C<IO::Zlib> is not installed.
  1535.  
  1536. You can use this as a shortcut to determine whether C<Archive::Tar>
  1537. will do what you think before passing compressed archives to its
  1538. C<read> method.
  1539.  
  1540. =cut
  1541.  
  1542. sub can_handle_compressed_files { return ZLIB ? 1 : 0 }
  1543.  
  1544. sub no_string_support {
  1545.     croak("You have to install IO::String to support writing archives to strings");
  1546. }
  1547.  
  1548. 1;
  1549.  
  1550. __END__
  1551.  
  1552. =head1 GLOBAL VARIABLES
  1553.  
  1554. =head2 $Archive::Tar::FOLLOW_SYMLINK
  1555.  
  1556. Set this variable to C<1> to make C<Archive::Tar> effectively make a
  1557. copy of the file when extracting. Default is C<0>, which
  1558. means the symlink stays intact. Of course, you will have to pack the
  1559. file linked to as well.
  1560.  
  1561. This option is checked when you write out the tarfile using C<write>
  1562. or C<create_archive>.
  1563.  
  1564. This works just like C</bin/tar>'s C<-h> option.
  1565.  
  1566. =head2 $Archive::Tar::CHOWN
  1567.  
  1568. By default, C<Archive::Tar> will try to C<chown> your files if it is
  1569. able to. In some cases, this may not be desired. In that case, set
  1570. this variable to C<0> to disable C<chown>-ing, even if it were
  1571. possible.
  1572.  
  1573. The default is C<1>.
  1574.  
  1575. =head2 $Archive::Tar::CHMOD
  1576.  
  1577. By default, C<Archive::Tar> will try to C<chmod> your files to
  1578. whatever mode was specified for the particular file in the archive.
  1579. In some cases, this may not be desired. In that case, set this
  1580. variable to C<0> to disable C<chmod>-ing.
  1581.  
  1582. The default is C<1>.
  1583.  
  1584. =head2 $Archive::Tar::DO_NOT_USE_PREFIX
  1585.  
  1586. By default, C<Archive::Tar> will try to put paths that are over 
  1587. 100 characters in the C<prefix> field of your tar header, as
  1588. defined per POSIX-standard. However, some (older) tar programs 
  1589. do not implement this spec. To retain compatibility with these older 
  1590. or non-POSIX compliant versions, you can set the C<$DO_NOT_USE_PREFIX> 
  1591. variable to a true value, and C<Archive::Tar> will use an alternate 
  1592. way of dealing with paths over 100 characters by using the 
  1593. C<GNU Extended Header> feature.
  1594.  
  1595. Note that clients who do not support the C<GNU Extended Header>
  1596. feature will not be able to read these archives. Such clients include
  1597. tars on C<Solaris>, C<Irix> and C<AIX>.
  1598.  
  1599. The default is C<0>.
  1600.  
  1601. =head2 $Archive::Tar::DEBUG
  1602.  
  1603. Set this variable to C<1> to always get the C<Carp::longmess> output
  1604. of the warnings, instead of the regular C<carp>. This is the same
  1605. message you would get by doing:
  1606.  
  1607.     $tar->error(1);
  1608.  
  1609. Defaults to C<0>.
  1610.  
  1611. =head2 $Archive::Tar::WARN
  1612.  
  1613. Set this variable to C<0> if you do not want any warnings printed.
  1614. Personally I recommend against doing this, but people asked for the
  1615. option. Also, be advised that this is of course not threadsafe.
  1616.  
  1617. Defaults to C<1>.
  1618.  
  1619. =head2 $Archive::Tar::error
  1620.  
  1621. Holds the last reported error. Kept for historical reasons, but its
  1622. use is very much discouraged. Use the C<error()> method instead:
  1623.  
  1624.     warn $tar->error unless $tar->extract;
  1625.  
  1626. =head2 $Archive::Tar::INSECURE_EXTRACT_MODE
  1627.  
  1628. This variable indicates whether C<Archive::Tar> should allow
  1629. files to be extracted outside their current working directory.
  1630.  
  1631. Allowing this could have security implications, as a malicious
  1632. tar archive could alter or replace any file the extracting user
  1633. has permissions to. Therefor, the default is to not allow 
  1634. insecure extractions. 
  1635.  
  1636. If you trust the archive, or have other reasons to allow the 
  1637. archive to write files outside your current working directory, 
  1638. set this variable to C<true>.
  1639.  
  1640. Note that this is a backwards incompatible change from version
  1641. C<1.36> and before.
  1642.  
  1643. =head2 $Archive::Tar::HAS_PERLIO
  1644.  
  1645. This variable holds a boolean indicating if we currently have 
  1646. C<perlio> support loaded. This will be enabled for any perl
  1647. greater than C<5.8> compiled with C<perlio>. 
  1648.  
  1649. If you feel strongly about disabling it, set this variable to
  1650. C<false>. Note that you will then need C<IO::String> installed
  1651. to support writing stringified archives.
  1652.  
  1653. Don't change this variable unless you B<really> know what you're
  1654. doing.
  1655.  
  1656. =head2 $Archive::Tar::HAS_IO_STRING
  1657.  
  1658. This variable holds a boolean indicating if we currently have 
  1659. C<IO::String> support loaded. This will be enabled for any perl
  1660. that has a loadable C<IO::String> module.
  1661.  
  1662. If you feel strongly about disabling it, set this variable to
  1663. C<false>. Note that you will then need C<perlio> support from
  1664. your perl to be able to  write stringified archives.
  1665.  
  1666. Don't change this variable unless you B<really> know what you're
  1667. doing.
  1668.  
  1669. =head1 FAQ
  1670.  
  1671. =over 4
  1672.  
  1673. =item What's the minimum perl version required to run Archive::Tar?
  1674.  
  1675. You will need perl version 5.005_03 or newer.
  1676.  
  1677. =item Isn't Archive::Tar slow?
  1678.  
  1679. Yes it is. It's pure perl, so it's a lot slower then your C</bin/tar>
  1680. However, it's very portable. If speed is an issue, consider using
  1681. C</bin/tar> instead.
  1682.  
  1683. =item Isn't Archive::Tar heavier on memory than /bin/tar?
  1684.  
  1685. Yes it is, see previous answer. Since C<Compress::Zlib> and therefore
  1686. C<IO::Zlib> doesn't support C<seek> on their filehandles, there is little
  1687. choice but to read the archive into memory.
  1688. This is ok if you want to do in-memory manipulation of the archive.
  1689. If you just want to extract, use the C<extract_archive> class method
  1690. instead. It will optimize and write to disk immediately.
  1691.  
  1692. =item Can't you lazy-load data instead?
  1693.  
  1694. No, not easily. See previous question.
  1695.  
  1696. =item How much memory will an X kb tar file need?
  1697.  
  1698. Probably more than X kb, since it will all be read into memory. If
  1699. this is a problem, and you don't need to do in memory manipulation
  1700. of the archive, consider using C</bin/tar> instead.
  1701.  
  1702. =item What do you do with unsupported filetypes in an archive?
  1703.  
  1704. C<Unix> has a few filetypes that aren't supported on other platforms,
  1705. like C<Win32>. If we encounter a C<hardlink> or C<symlink> we'll just
  1706. try to make a copy of the original file, rather than throwing an error.
  1707.  
  1708. This does require you to read the entire archive in to memory first,
  1709. since otherwise we wouldn't know what data to fill the copy with.
  1710. (This means that you cannot use the class methods on archives that
  1711. have incompatible filetypes and still expect things to work).
  1712.  
  1713. For other filetypes, like C<chardevs> and C<blockdevs> we'll warn that
  1714. the extraction of this particular item didn't work.
  1715.  
  1716. =item I'm using WinZip, or some other non-POSIX client, and files are not being extracted properly!
  1717.  
  1718. By default, C<Archive::Tar> is in a completely POSIX-compatible
  1719. mode, which uses the POSIX-specification of C<tar> to store files.
  1720. For paths greather than 100 characters, this is done using the
  1721. C<POSIX header prefix>. Non-POSIX-compatible clients may not support
  1722. this part of the specification, and may only support the C<GNU Extended
  1723. Header> functionality. To facilitate those clients, you can set the
  1724. C<$Archive::Tar::DO_NOT_USE_PREFIX> variable to C<true>. See the 
  1725. C<GLOBAL VARIABLES> section for details on this variable.
  1726.  
  1727. Note that GNU tar earlier than version 1.14 does not cope well with
  1728. the C<POSIX header prefix>. If you use such a version, consider setting
  1729. the C<$Archive::Tar::DO_NOT_USE_PREFIX> variable to C<true>.
  1730.  
  1731. =item How do I extract only files that have property X from an archive?
  1732.  
  1733. Sometimes, you might not wish to extract a complete archive, just
  1734. the files that are relevant to you, based on some criteria.
  1735.  
  1736. You can do this by filtering a list of C<Archive::Tar::File> objects
  1737. based on your criteria. For example, to extract only files that have
  1738. the string C<foo> in their title, you would use:
  1739.  
  1740.     $tar->extract( 
  1741.         grep { $_->full_path =~ /foo/ } $tar->get_files
  1742.     ); 
  1743.  
  1744. This way, you can filter on any attribute of the files in the archive.
  1745. Consult the C<Archive::Tar::File> documentation on how to use these
  1746. objects.
  1747.  
  1748. =item How do I access .tar.Z files?
  1749.  
  1750. The C<Archive::Tar> module can optionally use C<Compress::Zlib> (via
  1751. the C<IO::Zlib> module) to access tar files that have been compressed
  1752. with C<gzip>. Unfortunately tar files compressed with the Unix C<compress>
  1753. utility cannot be read by C<Compress::Zlib> and so cannot be directly
  1754. accesses by C<Archive::Tar>.
  1755.  
  1756. If the C<uncompress> or C<gunzip> programs are available, you can use
  1757. one of these workarounds to read C<.tar.Z> files from C<Archive::Tar>
  1758.  
  1759. Firstly with C<uncompress>
  1760.  
  1761.     use Archive::Tar;
  1762.  
  1763.     open F, "uncompress -c $filename |";
  1764.     my $tar = Archive::Tar->new(*F);
  1765.     ...
  1766.  
  1767. and this with C<gunzip>
  1768.  
  1769.     use Archive::Tar;
  1770.  
  1771.     open F, "gunzip -c $filename |";
  1772.     my $tar = Archive::Tar->new(*F);
  1773.     ...
  1774.  
  1775. Similarly, if the C<compress> program is available, you can use this to
  1776. write a C<.tar.Z> file
  1777.  
  1778.     use Archive::Tar;
  1779.     use IO::File;
  1780.  
  1781.     my $fh = new IO::File "| compress -c >$filename";
  1782.     my $tar = Archive::Tar->new();
  1783.     ...
  1784.     $tar->write($fh);
  1785.     $fh->close ;
  1786.  
  1787. =item How do I handle Unicode strings?
  1788.  
  1789. C<Archive::Tar> uses byte semantics for any files it reads from or writes
  1790. to disk. This is not a problem if you only deal with files and never
  1791. look at their content or work solely with byte strings. But if you use
  1792. Unicode strings with character semantics, some additional steps need
  1793. to be taken.
  1794.  
  1795. For example, if you add a Unicode string like
  1796.  
  1797.     # Problem
  1798.     $tar->add_data('file.txt', "Euro: \x{20AC}");
  1799.  
  1800. then there will be a problem later when the tarfile gets written out
  1801. to disk via C<$tar->write()>:
  1802.  
  1803.     Wide character in print at .../Archive/Tar.pm line 1014.
  1804.  
  1805. The data was added as a Unicode string and when writing it out to disk,
  1806. the C<:utf8> line discipline wasn't set by C<Archive::Tar>, so Perl
  1807. tried to convert the string to ISO-8859 and failed. The written file
  1808. now contains garbage.
  1809.  
  1810. For this reason, Unicode strings need to be converted to UTF-8-encoded
  1811. bytestrings before they are handed off to C<add_data()>:
  1812.  
  1813.     use Encode;
  1814.     my $data = "Accented character: \x{20AC}";
  1815.     $data = encode('utf8', $data);
  1816.  
  1817.     $tar->add_data('file.txt', $data);
  1818.  
  1819. A opposite problem occurs if you extract a UTF8-encoded file from a 
  1820. tarball. Using C<get_content()> on the C<Archive::Tar::File> object
  1821. will return its content as a bytestring, not as a Unicode string.
  1822.  
  1823. If you want it to be a Unicode string (because you want character
  1824. semantics with operations like regular expression matching), you need
  1825. to decode the UTF8-encoded content and have Perl convert it into 
  1826. a Unicode string:
  1827.  
  1828.     use Encode;
  1829.     my $data = $tar->get_content();
  1830.     
  1831.     # Make it a Unicode string
  1832.     $data = decode('utf8', $data);
  1833.  
  1834. There is no easy way to provide this functionality in C<Archive::Tar>, 
  1835. because a tarball can contain many files, and each of which could be
  1836. encoded in a different way.
  1837.  
  1838. =back
  1839.  
  1840. =head1 TODO
  1841.  
  1842. =over 4
  1843.  
  1844. =item Check if passed in handles are open for read/write
  1845.  
  1846. Currently I don't know of any portable pure perl way to do this.
  1847. Suggestions welcome.
  1848.  
  1849. =item Allow archives to be passed in as string
  1850.  
  1851. Currently, we only allow opened filehandles or filenames, but
  1852. not strings. The internals would need some reworking to facilitate
  1853. stringified archives.
  1854.  
  1855. =item Facilitate processing an opened filehandle of a compressed archive
  1856.  
  1857. Currently, we only support this if the filehandle is an IO::Zlib object.
  1858. Environments, like apache, will present you with an opened filehandle
  1859. to an uploaded file, which might be a compressed archive.
  1860.  
  1861. =back
  1862.  
  1863. =head1 SEE ALSO
  1864.  
  1865. =over 4
  1866.  
  1867. =item The GNU tar specification
  1868.  
  1869. C<http://www.gnu.org/software/tar/manual/tar.html>
  1870.  
  1871. =item The PAX format specication
  1872.  
  1873. The specifcation which tar derives from; C< http://www.opengroup.org/onlinepubs/007904975/utilities/pax.html>
  1874.  
  1875. =item A comparison of GNU and POSIX tar standards; C<http://www.delorie.com/gnu/docs/tar/tar_114.html>
  1876.  
  1877. =item GNU tar intends to switch to POSIX compatibility
  1878.  
  1879. GNU Tar authors have expressed their intention to become completely
  1880. POSIX-compatible; C<http://www.gnu.org/software/tar/manual/html_node/Formats.html>
  1881.  
  1882. =item A Comparison between various tar implementations
  1883.  
  1884. Lists known issues and incompatibilities; C<http://gd.tuwien.ac.at/utils/archivers/star/README.otherbugs>
  1885.  
  1886. =back
  1887.  
  1888. =head1 AUTHOR
  1889.  
  1890. This module by Jos Boumans E<lt>kane@cpan.orgE<gt>.
  1891.  
  1892. Please reports bugs to E<lt>bug-archive-tar@rt.cpan.orgE<gt>.
  1893.  
  1894. =head1 ACKNOWLEDGEMENTS
  1895.  
  1896. Thanks to Sean Burke, Chris Nandor, Chip Salzenberg, Tim Heaney and
  1897. especially Andrew Savige for their help and suggestions.
  1898.  
  1899. =head1 COPYRIGHT
  1900.  
  1901. This module is copyright (c) 2002 - 2007 Jos Boumans 
  1902. E<lt>kane@cpan.orgE<gt>. All rights reserved.
  1903.  
  1904. This library is free software; you may redistribute and/or modify 
  1905. it under the same terms as Perl itself.
  1906.  
  1907. =cut
  1908.